import React, { useEffect, useState } from 'react';
import { Tabs } from 'antd';
import { formatMessage } from 'umi';
import classNames from 'classnames';
import Modal from '@/zero/components/Modal';
import styles from './index.less';

const Index = (props) => {
  const {
    name,

    tabPanes = [],

    defaultActiveKey,
    // eslint-disable-next-line
    beforeChange = (resolve, reject) => {
      resolve();
    },
    onChange,

    disabled = false,

    removeConfirm = false, // 删除确认

    onAdd = () => {
      console.log(`onAdd`);
    },
    onRemove = (targetKey) => {
      console.log(`onRemove: ${targetKey}`);
    },

    className,
    ...rest
  } = props;

  const [activeKey, setActiveKey] = useState(null);

  const newTabPanes = tabPanes.map((item, index) => {
    const { key, id, title, content, ...itemRest } = item;
    return {
      key: key ? `${key}` : `${id || Date.now()}`,
      title,
      content: typeof content === 'function' ? content({ index, disabled: !!disabled }) : content,
      ...itemRest,
    };
  });

  const searchParams = new URL(window.location.href).searchParams;

  const newDefaultActiveKey = searchParams.get(name) || defaultActiveKey;
  const trigger = searchParams.get('trigger');

  useEffect(() => {
    if (newDefaultActiveKey) {
      setActiveKey(`${newDefaultActiveKey}`);
      if (onChange) {
        onChange(`${newDefaultActiveKey}`);
      }
    }
  }, [!!newDefaultActiveKey, trigger]);

  return (
    <Tabs
      destroyInactiveTabPane
      animated={false}
      {...rest}
      activeKey={activeKey || newTabPanes[0]?.key}
      onChange={(newActiveKey) => {
        new Promise((resolve, reject) => {
          beforeChange(resolve, reject);
        }).then(() => {
          setActiveKey(newActiveKey);
          if (onChange) {
            onChange(newActiveKey);
          }
        });
      }}
      className={classNames(styles.tabs, className)}
      type={disabled ? `${disabled.type || 'line'}` : 'editable-card'}
      onEdit={(targetKey, action) => {
        if (action === 'add' && onAdd) {
          onAdd();
        }
        if (action === 'remove' && onRemove) {
          if (removeConfirm) {
            Modal.confirm({
              title: formatMessage({ id: '删除提示' }),
              okText: formatMessage({ id: '确定' }),
              cancelText: formatMessage({ id: '取消' }),
              ...removeConfirm,
              onOk: () => {
                onRemove(targetKey);
              },
            });
          } else {
            onRemove(targetKey);
          }
        }
      }}
    >
      {newTabPanes.map((tabPane) => (
        <Tabs.TabPane forceRender={false} {...tabPane} key={tabPane.key} tab={tabPane.title}>
          {tabPane.content}
        </Tabs.TabPane>
      ))}
    </Tabs>
  );
};

Index.displayName = 'EditableTabs';
export default Index;
